import Vue from 'vue'
import Vuex from 'vuex'
import {getToken, removeToken,setToken} from "../api/util";
import {login} from "../api";

Vue.use(Vuex)

const state = {
  token: getToken(),
  userName: '',
  passWord: ''
};

const getters = {
  token(state){
    return state.token;
  }
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userName = userInfo.userName
    state.passWord = userInfo.passWord
  }
};

const actions = {
  Login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      login(userInfo).then(res => {
        const token = res.data.token;
        setToken(token)
        commit('SET_TOKEN', token)
        commit('SET_USERINFO', userInfo)
        resolve(res)
      }).catch(err => {
        reject(err)
      })

    })
  },
  // 前端 登出
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', '')
      removeToken()
      resolve()
    })
  }
}

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
